package cn.sxt.logistics.service.impl;

import cn.sxt.logistics.mapper.OrderDetailMapper;
import cn.sxt.logistics.pojo.Order;
import cn.sxt.logistics.mapper.OrderMapper;
import cn.sxt.logistics.pojo.OrderDetail;
import cn.sxt.logistics.service.IOrderService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-06-24
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 新增修改订单思路
     *
     * 1，先将订单基础信息插入到订单表中，并获取数据库生成的订单id
     *
     * 2，删除订单明细表中原有的订单数据
     *
     * 3，循环订单明细，将获取的订单id设置给每一个订单明细对象
     * 4，循环插入订单明细
     */
    @Override
    public boolean insertOrUpdate(Order order) {

        //先将订单基础信息插入到订单表中，并获取数据库生成的订单id
        boolean flag = this.saveOrUpdate(order);

        //删除订单明细表中原有的订单数据
        UpdateWrapper<OrderDetail> wrapper = new UpdateWrapper<>();
        wrapper.eq("order_id",order.getOrderId());
        orderDetailMapper.delete(wrapper);

        List<OrderDetail> orderDetails = order.getOrderDetails();
        for (OrderDetail orderDetail : orderDetails) {
            //循环订单明细，将获取的订单id设置给每一个订单明细对象
            orderDetail.setOrderId(order.getOrderId());
            //循环插入订单明细
            orderDetailMapper.insert(orderDetail);
        }
        return flag;
    }
}
